//   
//   UIImage+Extensions.swift
//   BaseComponetKit
//   Created  by monkey on 2024/4/3
//   
//   

import UIKit
import UIKit

extension UIImage {
    func averageColorInCenter() -> UIColor? {
        // 1. 缩小图片以加快计算速度，但需要注意结果误差可能增大
        guard let resizedImage = resizeTo(CGSize(width: 40, height: 40)) else { return nil }
        
        // 2. 取每个点的像素值
        guard let pixelData = resizedImage.pixelData() else { return nil }
        
        // 3. 找到出现次数最多的颜色
        guard let mostFrequentColor = mostFrequentColor(in: pixelData) else { return nil }
        
//        // 4. 如果出现的是白色，去掉白色，选择第二多颜色
//        if mostFrequentColor == UIColor.white {
//            let colorCounts = pixelData.reduce(into: [:]) { counts, color in counts[color, default: 0] += 1 }
//            let secondFrequentColor = colorCounts.sorted { $0.value > $1.value }.dropFirst().first?.key
//            return secondFrequentColor
//        }
//        
        return mostFrequentColor
    }
    
    // 缩小图片以加快计算速度，但需要注意结果误差可能增大
    private func resizeTo(_ newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    // 取每个点的像素值
    private func pixelData() -> [UIColor]? {
        guard let cgImage = self.cgImage else { return nil }
        
        let width = cgImage.width
        let height = cgImage.height
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        var pixelsData = [UIColor]()
        
        guard let context = CGContext(data: nil,
                                      width: width,
                                      height: height,
                                      bitsPerComponent: 8,
                                      bytesPerRow: bytesPerRow,
                                      space: colorSpace,
                                      bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) else {
            return nil
        }
        
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        
        if let rawData = context.data {
            let buffer = UnsafeBufferPointer<UInt8>(start: rawData.bindMemory(to: UInt8.self, capacity: width * height * bytesPerPixel), count: width * height * bytesPerPixel)
            
            for i in stride(from: 0, to: buffer.count, by: bytesPerPixel) {
                let red = CGFloat(buffer[i]) / 255.0
                let green = CGFloat(buffer[i + 1]) / 255.0
                let blue = CGFloat(buffer[i + 2]) / 255.0
                let alpha = CGFloat(buffer[i + 3]) / 255.0
              
                
                let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                // 如果像素不是完全透明且不是接近白色，则添加到像素数据数组中
                if alpha > 0.1 && !(red > 0.9 && green > 0.9 && blue > 0.9) {
                                pixelsData.append(color)
                            }
            }
        }
        
        return pixelsData
    }
    
    // 找到出现次数最多的颜色
    private func mostFrequentColor(in colors: [UIColor]) -> UIColor? {
        var colorCounts: [UIColor: Int] = [:]
        
        for color in colors {
            if let count = colorCounts[color] {
                colorCounts[color] = count + 1
            } else {
                colorCounts[color] = 1
            }
        }
        
        let mostFrequentColor = colorCounts.max { $0.value < $1.value }?.key
        
        return mostFrequentColor
    }
}
